<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;

class InstPerson extends Model
{
    protected $table = 'dd_instperson';
    protected $primaryKey = 'id';
    public $timestamps = false;
    protected $guarded = array();
    
    /**
     * 添加用户
     * @param \Illuminate\Http\Request $request
     * @return type
     */
    public static function addInstPer(\Illuminate\Http\Request $request) {
        $ipdata['name'] = $request->input('name');
        $ipdata['phone'] = $request->input('phone');
        $ipdata['password'] = md5($request->input('password'));
        $instper = static::firstOrCreate($ipdata);
        if ($instper) {
            if ($request->has('plots')) {
                $iplotdata = array_map(function($val) use ($instper) {
                    return array('plotid'=>$val, 'iperid'=>$instper->id);
                }, $request->input('plots'));
                $res = Iperplot::insert($iplotdata);
                return $res ? ['status'=>1, 'info'=>'添加成功，分配管理小区成功'] : ['status'=>1, 'info'=>'添加成功，分配管理小区失败'];
            }
            return array('status'=>1, 'info'=>'添加成功');
        } else {
            return array('status'=>0, 'info'=> '添加失败');
        }
    }
    /**
     * 管理小区
     */
    public function strPlot() {
        $plots = Iperplot::where('iperid', $this->id)
                ->leftJoin('dd_plot', 'dd_iperplot.plotid', '=', 'dd_plot.id')
                ->select('dd_plot.name')
                ->get();
        if (count($plots)) {
            $iplot = "";
            foreach ($plots as $val) {
                $iplot .= "<kbd>".$val->name."</kbd> ";
            }
            return $iplot;
        } else {
            return "<span class='text-warning'>没有分配管理小区</span>";
        }
    }
}
